/**
 * 系统名称: 企业财资
 * 模块名称: repair-boot
 * 类 名 称: WxLoginController.java
 * 软件版权: 恒生电子股份有限公司
 * 修改记录:
 * 修改人员:
 * 修改说明:
 * ============ ============================================
 * zhanghong 创建
 * ============ ============================================
 */
package com.mt.common.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mt.common.core.config.Config;
import com.mt.common.core.utils.StringUtils;
import com.mt.common.system.service.WxService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 *
 *
 * @author zhanghong
 * @date 2023-03-13 21:20
 */
@Api(tags = "微信登陆")
@RestController
@RequestMapping("/api/wx")
@CrossOrigin(allowCredentials = "true")
public class WxLoginController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxService wxService;

    @PostMapping("login")
    public Map<String,Object> wxLogin(@RequestParam("code") String code,@RequestParam String encryptedData,@RequestParam String iv) throws Exception {
        Map<String,Object> result = new HashMap<>();
        result.put("status",200);
        String url="https://api.weixin.qq.com/sns/jscode2session?" +
                "appid="+Config.APPID +
                "&secret="+Config.APPSECRET +
                "&js_code="+code +
                "&grant_type=authorization_code";
        String jsonData = restTemplate.getForObject(url, String.class);
        //System.out.println("**jsonData**:"+jsonData); //打印jsonData
        if (StringUtils.contains(jsonData,"errcode")){
            result.put("status",500);
            result.put("msg","登录失败");
            return result;
        }
        JSONObject jsonObject= JSONObject.parseObject(jsonData);
        String s = wxService.wxDecrypt(encryptedData, jsonObject, iv);
        JSONObject jsonObject1 = JSON.parseObject(s);
        //redisTemplate.opsForValue().set("wxLogin",jsonData, 5,TimeUnit.HOURS);  //存到redis五个小时过期
        result.put("ticket","HZZ_"+jsonData); //session_key和openid不应该返回到客户端，这里我只是方便测试
        return result;
    }
}
